<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="RolesVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <el-table :data="rolelist" border stripe>
        <el-table-column type="expand">
          <template v-slot="scope">
            <el-row
              class="bdbottom vcenter"
              v-for="item1 in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag
                  type="primary"
                  @close="removeRightById(scope.row, item1.id)"
                  closable
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <el-row
                  class="bdtop vcenter"
                  v-for="item2 in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      closable
                      type="success"
                      @close="removeRightById(scope.row, item2.id)"
                    >
                      {{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="角色" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template v-slot="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="showRoleForm(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="deleteRole(scope.row.id)"
              >删除</el-button
            >
            <el-button
              type="warning"
              size="mini"
              icon="el-icon-setting"
              @click="setRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加编辑角色弹框 -->
    <el-dialog
      :title="title"
      :visible.sync="RolesVisible"
      width="50%"
      @close="RolesClose"
    >
      <el-form
        ref="RolesRef"
        :model="RolesForm"
        :rules="RolesRules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="RolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="RolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="RolesVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleForm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限的对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightDialogClosed"
    >
      <el-tree
        :data="rightsList"
        :props="treeProps"
        ref="treeRef"
        node-key="id"
        default-expand-all
        show-checkbox
        :default-checked-keys="defKeys"
      >
      </el-tree>
      <div slot="footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRights()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //所有的角色列表数据
      rolelist: [],
      //添加角色表单的显示
      RolesVisible: false,
      RolesForm: {
        roleId: null,
        roleName: '',
        roleDesc: ''
      },
      title: '添加角色',
      //控制分配权限对话框的显示隐藏
      setRightDialogVisible: false,
      //权限列表
      rightsList: [],
      //树形控件的绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      //默认选中 的节点id值
      defKeys: [],
      currentRoleId: null,
      RolesRules: {
        roleName: [
          { required: true, message: '角色名称', trigger: 'blur' },
          { min: 3, max: 10, message: '角色名称的长度在3~10之间', trigger: 'blur' },
        ],
        roleDesc: [
          { min: 3, max: 20, message: '角色描述的长度在3~20之间', trigger: 'blur' },
        ]
      }
    }
  },
  created() {
    this.getRoleslist()
  },
  methods: {
    //获取角色列表
    async getRoleslist() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.meg)
      this.rolelist = res.data
    },
    //监听添加角色对话框的关闭事件
    RolesClose() {
      this.$refs.RolesRef.resetFields()
      this.title = '添加角色'
      this.RolesForm.roleId = null
    },
    //展示修改表单
    async showRoleForm(id) {
      this.title = '编辑角色'
      this.RolesVisible = true
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.RolesForm = res.data

    },
    //保存和编辑角色
    saveRoleForm() {
      this.$refs.RolesRef.validate(async valid => {
        if (!valid) return

        if (!this.RolesForm.roleId) {
          //可以发起添加角色的网络请求
          const { data: res } = await this.$http.post('roles', this.RolesForm)
          if (res.meta.status !== 201) {
            this.RolesVisible = false
            return this.$message.error("添加新角色失败")
          }
          this.$message.success("添加新角色成功")
        } else {
          const { data: res } = await this.$http.put('roles/' + this.RolesForm.roleId, this.RolesForm)
          console.log(res);
          if (res.meta.status !== 200) {
            this.RolesVisible = false
            return this.$message.error("修改角色失败")
          }
          this.$message.success("修改角色成功")
        }
        this.RolesVisible = false
        this.getRoleslist()
      })

    },
    //删除角色
    async deleteRole(id) {
      //方案1
      // const result = this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // }).then(async () => {
      //   const { data: res } = await this.$http.delete('roles/' + id)
      //   if (res.meta.status !== 200) {
      //     return this.$message.error("删除角色失败")
      //   }
      //   this.$message({
      //     type: 'success',
      //     message: '删除成功!'
      //   })
      //   this.getRoleslist()
      // }).catch(() => {
      //   this.$message({
      //     type: 'info',
      //     message: '已取消删除'
      //   })
      // })
      //方案2  直接用函数返回值判断
      const result = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (result !== 'confirm') {
        return this.$message.info("已取消删除")
      }
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error("删除角色失败")
      }
      this.$message.success("删除角色成功")
      this.getRoleslist()
    },
    //根据id删除对应的权限
    removeRightById(role, roleId) {
      //弹框提示用户是否删除
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${roleId}`)
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        //双向绑定  局部刷新
        role.children = res.data

        //请求 全局刷新 权限会被合并
        // this.getRoleslist()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })

    },
    //展示分配权限的对话框
    async setRightDialog(role) {
      this.currentRoleId = role.id
      //获取所有权限的数据
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        this.$message.error('获取权限数据失败')
      }
      this.rightsList = res.data
      // console.log(this.rightsList);
      // console.log(role);
      // this.defKeys = []
      this.getLeafKeys(role, this.defKeys)
      this.setRightDialogVisible = true
    },
    //通过递归的形式，获取角色下所有三级权限的id，
    //并保存到 defKeys数组中
    getLeafKeys(node, arr) {

      //如果当前node节点不包含children属性，则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(element => {
        this.getLeafKeys(element, arr)
      });
    },
    //关闭分配权限对话框的关闭事件
    setRightDialogClosed() {
      this.defKeys = []
    },
    //点击为角色分配权限
    async saveRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()

      ]
      console.log(keys);
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.currentRoleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功')
      this.getRoleslist()
      this.setRightDialogVisible = false
    }

  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdtop:nth-child(1) {
  border: none;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.bdbottom:nth-child(1) {
  border-top: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>